package com.jourwon.spring.boot.controller;

import com.alibaba.fastjson.JSON;
import com.jourwon.spring.boot.prop.MultiDataSourceProperties;
import com.jourwon.spring.boot.prop.UserProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 加载配置文件controller
 *
 * @author JourWon
 * @date 2021/2/11
 */
@RestController
@Api(tags = "加载配置文件")
@RequestMapping("/prop")
@Configuration
@EnableConfigurationProperties(value = {UserProperties.class})
public class PropertiesController {

    public static final String DEFAULT_VALUE = "hello world";

    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${my-project.value:#{T(com.jourwon.spring.boot.controller.PropertiesController).DEFAULT_VALUE}}")
    private String value;

    @Resource
    private Environment env;

    @Resource
    private UserProperties userProperties;

    @Resource
    private MultiDataSourceProperties multiDataSourceProperties;

    @GetMapping("/application-name1")
    @ApiOperation("通过@Value注解获取配置")
    public String applicationName1() {
        return applicationName;
    }

    @GetMapping("/application-name2")
    @ApiOperation("通过环境变量获取配置")
    public String applicationName2() {
        return env.getProperty("spring.application.name");
    }

    @GetMapping("/application-name3")
    @ApiOperation("通过类属性获取配置")
    public String applicationName3() {
        return value;
    }

    @GetMapping("/user-config")
    @ApiOperation("对象配置")
    public String userList() {
        return JSON.toJSONString(userProperties);
    }

    @GetMapping("/multi-data-source-config")
    @ApiOperation("多数据源配置")
    public String multiDataSourceConfig() {
        return JSON.toJSONString(multiDataSourceProperties);
    }

}
